#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/20 18:03
# @Author  : Tom_zc
# @FileName: majun_helper.py
# @Software: PyCharm
import time
import logging
import base64
import hashlib
import hmac

import request_handler

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")


class PoisonHelper:
    poison_url = "{}/gateway/openlibing-anti-poison/poison-pr/sca-pr"
    poison_status_url = "{}/gateway/openlibing-anti-poison/poison-pr/query-pr-results-status"

    def __init__(self, appId, secretKey, domain, request_handler=request_handler.RequestHandler()):
        self.appId = appId
        self.appKey = secretKey
        self.domain = domain
        self.request_handler = request_handler

    def refresh_sign(self, timestamp):
        hmac_string = self.appId + timestamp
        hmac_hash = hmac.new(self.appKey.encode(), hmac_string.encode(), digestmod=hashlib.sha256)
        hmac_base64 = base64.b64encode(hmac_hash.digest()).decode()
        return hmac_base64

    def create_task(self, pr_url):
        timestamp = str(int(time.time() * 1000))
        headers = {
            "Content-Type": "application/json",
            "accountid": self.appId,
            "timestamp": timestamp,
            "sign": self.refresh_sign(timestamp)
        }
        data = {
            "prUrl": pr_url,
            "projectName": "openUBMC"
        }
        _, resp = self.request_handler.post(self.poison_url.format(self.domain), json_data=data, headers=headers)
        if not str(resp.get("code")).startswith("20"):
            raise Exception("create task failed:{}".format(resp.get("message")))
        return resp["result"]["scanId"]

    def check_task(self, task_id):
        count = 0
        while True:
            timestamp = str(int(time.time() * 1000))
            headers = {
                "Content-Type": "application/json",
                "accountid": self.appId,
                "timestamp": timestamp,
                "sign": self.refresh_sign(timestamp)
            }
            data = {
                "scanId": task_id
            }
            _, resp = self.request_handler.post(self.poison_status_url.format(self.domain), json_data=data, headers=headers)
            detail_code = int(resp["code"])
            if detail_code == 200:
                if resp["result"]:
                    logging.info("return codeCheck result:{}".format(resp["result"]))
                    if resp["result"]["isPass"]:
                        return "PASS", resp["result"]["url"]
                    return "Failed", resp["url"]
                logging.info("waiting for return codeCheck result for majun platform and count:{}.....".format(count))
                time.sleep(10)
                count += 1
            else:
                return "Failed", resp["message"]

            if count > 10 * 60 / 5:
                return "Timeout", resp["message"]